<template>
  <view class="box-wp">
    <view class="goods-main-img">
      <image mode="widthFix" class="main-img" :src="goodsInfo.pic">
      </image>
      <view class="goods-info">
        <view class="title u-line-1">
          {{ goodsInfo.prodName || "" }}
        </view>
        <view class="price-wp" v-if="goodsInfo.price||goodsInfo.price===0">
          ￥ {{ goodsInfo.price || "" }}
        </view>
        <text class="goods-tag" v-if="goodsInfo.voucher==1">可用代金券</text>
      </view>
      <view class="padding-bar">
      </view>
    </view>
    <view class="goods-main-info">
      <view class="sell" v-if="showBuyBtn">
        <view class="avatar">
          <u--image shape="circle" v-if="goodsInfo.shopLogo" :src="goodsInfo.shopLogo" width="64rpx"
                    height="64rpx"></u--image>
          <u--image shape="circle"
                    src="https://file.casugn.com/storecompcard/temp/男_1705454811406.png" v-else
                    width="64rpx" height="64rpx"></u--image>
        </view>
        <view class="sell-name">
          {{ goodsInfo.shopName || "" }}
          <!--          <text class="friend-tag" v-if="goodsInfo.buddy==1">好友</text>-->
        </view>
      </view>

      <view class="info">
        <view class="title1">商品单位：</view>
        <view class="title2">
          {{ goodsInfo.units || "" }}
        </view>
      </view>
      <view class="info" v-if="goodsInfo.brief">
        <view class="title1">产品介绍：</view>
        <text class="title2" space="nbsp">
          {{ goodsInfo.brief || "" }}
        </text>
      </view>
    </view>
    <!-- Tab切换区域 -->
    <view class="tab-section" v-if="goodsInfo && goodsInfo.id">
      <view class="custom-tabs">
        <view
            class="tab-item"
            :class="{ active: currentTab === 0 }"
            @click="onTabChange(0)"
        >
          商品详情
        </view>
        <view
            class="tab-item"
            :class="{ active: currentTab === 1 }"
            @click="onTabChange(1)"
        >
          商品评价
        </view>
      </view>

      <!-- 商品详情内容 -->
      <view class="tab-content" v-if="currentTab === 0">
        <view class="goods-detail" v-if="gooodsDetailImg.length>0">
          <view class="imgs" v-for="item in gooodsDetailImg" :key="item">
            <image :src="item.url" style="width: 750rpx;" mode="widthFix"></image>
          </view>
        </view>
        <view class="no-content" v-else>
          <image class="cover"
                 src="https://file.casugn.com/storecompcard/temp/npj_1758159696516.png"
                 mode="aspectFill"></image>
          <text>暂无商品详情</text>
        </view>
      </view>

      <!-- 商品评价内容 -->
      <view class="tab-content" v-if="currentTab === 1">
        <view class="comment-list" v-if="commentList.length > 0">
          <view class="comment-item" v-for="comment in commentList" :key="comment.id">
            <view class="comment-header">
              <image class="user-avatar"
                     :src="comment.userHead || 'https://file.casugn.com/storecompcard/temp/男_1705454811406.png'"
                     mode="aspectFill"></image>
              <view class="user-info">
                <text class="user-name">
                  {{ comment.isAnonymous ? '匿名用户' : (comment.userId_dictText || '用户') }}
                </text>
                <view class="comment-meta">
                  <u-rate :value="comment.score" count="5" size="24" activeColor="#ff9f1a"
                          inactiveColor="#eee" readonly></u-rate>
                  <text class="comment-time">{{ formatTime(comment.createTime) }}</text>
                </view>
              </view>
            </view>
            <view class="comment-content">{{ comment.content }}</view>
          </view>
        </view>
        <view class="no-content" v-else>
          <image class="cover"
                 src="https://file.casugn.com/storecompcard/temp/npj_1758159696516.png"
                 mode="aspectFill"></image>
          <text>暂无商品评价</text>
        </view>
      </view>
    </view>

    <template v-if="!fromGiftDetail">
      <view class="bottom-box" v-if="showBuyBtn">
        <view class="left-actions">
          <view class="shop-box" @click="goShop">
            <image class="cover"
                   src="https://file.casugn.com/storecompcard/temp/dpp_1758013057930.png"
                   mode="aspectFill"></image>
            <text class="shop-text">店铺</text>
          </view>
          <view class="shop-box" @click="goService">
            <image class="cover"
                   src="https://file.casugn.com/storecompcard/temp/kf_1758013677747.png"
                   mode="aspectFill"></image>
            <text class="shop-text">客服</text>
          </view>
        </view>
        <u-button @click="order" :custom-style="{
				  background: '#276aee',
				  color: '#fff',
				  border:'none',
				  height:'88rpx',
				  lineHeight:'88rpx',
				  borderRadius:'44rpx',
				  fontSize:'30rpx',
				  marginLeft:'10rpx',
				  flex: 0.9
				}">购买
        </u-button>
      </view>
      <view class="bottom-box" v-else>
        <u-button openType="share" :custom-style="{
				  background: '#276aee',
				  color: '#fff',
				  width: '682rpx',
				  border:'none'
				}">分享赠送
        </u-button>

      </view>
    </template>

  </view>
</template>

<script>
import {
  mapState,
  mapGetters
} from 'vuex'

export default {
  data() {
    return {
      goodsId: '',
      goodsInfo: {},
      gooodsDetailImg: [],
      showBuyBtn: true,
      goodsOwnerOpenId: '',
      fromGiftDetail: false,
      currentTab: 0, // 当前激活的tab索引
      commentList: [] // 评价列表
    };
  },
  onLoad(opt) {
    if (opt.id) {
      console.log(opt, 'option');
      this.goodsId = opt.id
      this.goodsOwnerOpenId = opt.openId
      this.showBuyBtn = opt.hiddenBuyBtn == 1 ? false : true
      this.fromGiftDetail = opt.fromGiftDetail == 1 ? true : false
      this.getGoodsInfo()
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    goShop() {
      console.log('点击店铺了', this.goodsInfo)
      // 优先使用商品返回的 shopId，其次 cardId，最后使用 openId 作为兜底
      if (this.goodsInfo && this.goodsInfo.shopId) {
        uni.navigateTo({url: `/pagesMall/myShop/shopInfo?shopId=${this.goodsInfo.shopId}`})
      } else if (this.goodsInfo && this.goodsInfo.cardId) {
        uni.navigateTo({url: `/pagesMall/myShop/shopInfo?cardId=${this.goodsInfo.cardId}`})
      } else {
        uni.navigateTo({url: `/pagesMall/myShop/shopInfo?openId=${this.goodsOwnerOpenId}`})
      }
    },
    goService() {
      console.log('打开聊天:', this.goodsInfo)
      uni.navigateTo({
        url:
            `/pagesMall/mallCenter/messageDetail?cardId=${this.goodsInfo.cardId}&openId=${this.goodsInfo.openId}&name=${this.goodsInfo.shopName}&shopId=${this.goodsInfo.shopId} `
      })
    },
    order() {
      uni.navigateTo({
        url:
            `/pagesMall/mallCenter/order?goodsId=${this.goodsId}&openId=${this.goodsOwnerOpenId}`
      })
    },
    callMe() {
      if (this.goodsInfo.shopMobile) {
        this.goodsInfo.shopMobile = this.goodsInfo.shopMobile + ''
        uni.makePhoneCall({
          phoneNumber: this.goodsInfo.shopMobile
        })
      } else {
        uni.showToast({
          title: '未留联系方式',
          icon: 'none'
        })
      }
    },
    async getGoodsInfo() {
      uni.showLoading({
        title: 'loading'
      })
      let res = await this.$api.getProdShopDetail({
        id: this.goodsId,
        openId: this.goodsOwnerOpenId
      })
      if (res.success) {
        console.log(res.result);
        this.goodsInfo = res.result
        let fileListImgs = []
        if (this.goodsInfo.images && this.goodsInfo.images.length > 0) {
          if (this.goodsInfo.images.indexOf(',') == -1) {
            fileListImgs.splice(0, 1, this.goodsInfo.images)
          } else {
            fileListImgs = this.goodsInfo.images.split(',')
          }
          this.gooodsDetailImg = fileListImgs.map(item => {
            if (item.length > 1) {
              let newItem = {
                url: item,
                filePath: item
              }
              return newItem
            }
          })
        }

      } else {
        this.goodsInfo = {}
        uni.showToast({
          icon: 'none',
          title: res.message
        })
      }
      uni.hideLoading()
    },

    // 切换tab
    onTabChange(index) {
      this.currentTab = index
      if (index === 1 && this.commentList.length === 0) {
        this.getCommentList()
      }
    },

    // 获取评价列表
    async getCommentList() {
      try {
        const res = await this.$api.getMssdsProdCommList({
          shopId: this.goodsId, //商品的id
          pageNo: 1,
          pageSize: 20
        })
        if (res.success) {
          this.commentList = res.result.records || []
        }
      } catch (error) {
        console.error('获取评价列表失败8888:', error)
        uni.showToast({
          title: '获取评价失败',
          icon: 'none'
        })
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

  },
  onShareAppMessage(e) {
    console.log(e);
    if (e.from == 'menu') {
      uni.showToast({
        icon: 'none',
        title: '请点击下方分享按钮分享'
      })
      return
    }
    if (!this.userInfo.id) {
      uni.showToast({
        title: '请先创建名片',
        icon: 'none'
      })
      return
    }
    uni.showLoading({})
    let that = this
    if (!that.showBuyBtn) {
      //赠送模式
      let promise = new Promise(resolve => {
        let {
          openId,
        } = that.userInfo

        let shopType = that.goodsInfo.voucher == 1 ? 1 : 0
        let payload = {
          prodId: that.goodsInfo.id,
          shopType
        }
        this.$api.addProductGive(payload).then(res => {
          uni.hideLoading()
          if (res.success) {
            console.log(res.result, 'res');
            resolve({
              title: `${that.goodsInfo.shopUser ? that.goodsInfo.shopUser : '您的好友'}赠送给您${that.goodsInfo.prodName ? that.goodsInfo.prodName : '礼物'}`,
              path: `/pagesMall/sharePage/sharePage?orderId=${res.result.id}&openId=${that.goodsOwnerOpenId}`,
              imageUrl: that.goodsInfo.pic,
            })
          } else {
            uni.showToast({
              title: '生成分享页面失败,引导进入首页',
              icon: 'none'
            })
          }
        })
      })
      return {
        promise,
        title: `我的拜帖`,
        path: '/pages/card/card',
      }
    } else {

    }

  },
}
</script>
<style lang="scss" scoped>
.box-wp {
  padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);

  .goods-main-img {
    .main-img {
      width: 750rpx;
    }

    .goods-info {
      margin-top: -10rpx;
      border-radius: 16rpx 16rpx 0rpx 0rpx;
      padding: 32rpx;
      z-index: 2;

      .goods-tag {
        border-radius: 6rpx;
        border: 1rpx solid #FF7D00;
        padding: 4rpx 10rpx;
        text-align: center;
        width: 100rpx;
        height: 28rpx;
        font-size: 20rpx;
        font-weight: 400;
        color: #FF7D00;
        line-height: 28rpx;

      }

      .title {
        width: 740rpx;
        height: 44rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: #1D2129;
        line-height: 45rpx;

      }

      .price-wp {
        margin-top: 20rpx;
        height: 50rpx;
        font-size: 36rpx;
        font-weight: 600;
        color: #FF3131;
        line-height: 50rpx;

      }
    }

    .padding-bar {
      height: 40rpx;
      background-color: #f7f8fa;
    }

  }

  .goods-main-info {
    padding: 32rpx;

    .sell {
      height: 64rpx;
      display: flex;

      .sell-name {
        margin-left: 20rpx;
        height: 60rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #1D2129;
        line-height: 60rpx;

        .friend-tag {
          margin-left: 16rpx;
          text-align: center;
          display: inline-block;
          width: 80rpx;
          height: 34rpx;
          font-size: 20rpx;
          font-weight: 400;
          color: #4E5969;
          line-height: 34rpx;
          border: 1rpx solid #E5E6EB;
          border-radius: 6rpx;


        }
      }
    }

    .info {
      margin-top: 30rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #4E5969;
      display: flex;


      .title1 {
        width: 180rpx;
      }

      .title2 {
        flex: 1;
        font-size: 28rpx;
        font-weight: 400;
        color: #1D2129;
        line-height: 39rpx;
        word-break: break-word;
      }
    }
  }

  .tab-section {
    background: #fff;

    .custom-tabs {
      display: flex;
      background: #f7f8fa;
      border-bottom: 1rpx solid #e5e6eb;

      .tab-item {
        flex: 1;
        text-align: center;
        height: 96rpx;
        line-height: 96rpx;
        font-size: 28rpx;
        color: #4e5969;
        position: relative;
        transition: all 0.3s ease;

        &.active {
          color: #276aee;
          font-weight: 600;

          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 4rpx;
            background: #276aee;
            border-radius: 2rpx;
          }
        }
      }
    }

    .tab-content {
      min-height: 200rpx;

      .goods-detail {
        .imgs {
          // 保持原有样式
        }
      }

      .comment-list {
        padding: 20rpx;

        .comment-item {
          padding: 20rpx 0;
          border-bottom: 1rpx solid #f0f2f5;

          &:last-child {
            border-bottom: none;
          }

          .comment-header {
            display: flex;
            align-items: flex-start;
            margin-bottom: 12rpx;

            .user-avatar {
              width: 60rpx;
              height: 60rpx;
              border-radius: 50%;
              margin-right: 16rpx;
            }

            .user-info {
              flex: 1;

              .user-name {
                font-size: 26rpx;
                color: #1d2129;
                font-weight: 500;
                margin-bottom: 8rpx;
                display: block;
              }

              .comment-meta {
                display: flex;
                align-items: center;
                gap: 12rpx;

                .comment-time {
                  font-size: 22rpx;
                  color: #86909c;
                }
              }
            }
          }

          .comment-content {
            font-size: 26rpx;
            color: #4e5969;
            line-height: 1.5;
            margin-left: 76rpx;
          }
        }
      }

      .no-content {
        text-align: center;
        padding: 60rpx 20rpx;
        color: #86909c;
        font-size: 26rpx;
        margin-top: 50rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 20rpx;

        .cover {
          width: 100rpx;
          height: 100rpx;
        }
      }
    }
  }


}

.bottom-box {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  padding: 16rpx 24rpx 20rpx;
  background: #ffffff;
  border-top: 2rpx solid #f0f2f5;
  box-shadow: 0 -6rpx 20rpx rgba(0, 0, 0, 0.06);
}

.left-actions {
  display: flex;
  //gap: 24rpx;
}

.left-actions .shop-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 90rpx;
  height: 100rpx;
}

.left-actions .shop-box:active {
  opacity: 0.9;
}

.left-actions .shop-box .cover {
  width: 44rpx;
  height: 44rpx;
}

.left-actions .shop-box .shop-text {
  margin-top: 6rpx;
  font-size: 22rpx;
  color: #276aee;
}
</style>
